﻿using System;
using System.Collections.Generic;
using System.Text;
using AppSocketService.Relay;
using System.Threading;
using BCGPSCommon;
using AppSocketModel;
using System.Net;

namespace BCGPS.DataRealy.Service
{
    public class MainRelay
    {
        private readonly IRelayService relayService;
        private List<RelayDto> relayList;

        private ReadKafakaConsumer readKafakaConsumer = null;
        private Dictionary<int, UdpDataSendClient> udpDataSendClientDict = null;

        public MainRelay()
        {
            this.relayService = new RelayService();
            udpDataSendClientDict = new Dictionary<int, UdpDataSendClient>();
            readKafakaConsumer = new ReadKafakaConsumer(udpDataSendClientDict);

        }

        public void Run()
        {
            udpDataSendClientDict.Clear();

            relayList = relayService.GetAll();

            foreach (var item in relayList)
            {
                if (item.RelayControlCmdState == RelayControlCmdState.COMPLETE && item.RelayServerRunState == RelayServerRunState.RUN)
                {
                    var udpDataSendClient = new UdpDataSendClient(item);
                    udpDataSendClientDict.Add(item.CompanyId, udpDataSendClient);
                }
            }
            readKafakaConsumer.Start();

            while (true)
            {
                var list = relayService.GetRunningCommond();

                foreach(var item in list)
                {
                    Msg.WirteLine($"有新的控制命令CompanyId:={item.CompanyId} , 服务状态:={item.RelayControlCmdState.ToString()}", 0);
                    if (udpDataSendClientDict.ContainsKey(item.CompanyId))
                    {
                        udpDataSendClientDict[item.CompanyId].ResetIPEndPoint(IPAddress.Parse(item.RelayUrl), item.Port); 
                    }
                    else
                    {
                        var udpDataSendClient = new UdpDataSendClient(item);
                        udpDataSendClientDict.Add(item.CompanyId, udpDataSendClient);
                    }

                    relayService.SetCmdRunState(item.CompanyId, RelayControlCmdState.COMPLETE);
                    relayService.SetServerRunState(item.CompanyId, RelayServerRunState.RUN);
                }
                Thread.Sleep(1000);
            }
        }
    }
}
